<template>
  <div class="piaomake">
    <!-- <a class="goTop" href="#">返回顶部</a> -->
    <div style="position: relative;">
      <div class="clearfix" style="margin-bottom: 6px;">

        <div style="float: right;">
          <el-button
            type="success"
            size="mini"
            @click="goBack"
          >返回
          </el-button>
          <!--v-hasPermi="['hr:invoice:summary:completed']"-->
          <el-button v-hasPermi="['hr:invoice:refund:summary:completed']" size="mini" type="warning" @click="handleOk" v-show="handleOkVisible && !completedFlag">已完成</el-button>
    
          <el-button
            type="primary"
            size="mini"
            @click="handleSave"
            v-if="(type!=='3' || isTuiPiao)  && !tuiPiaoVal.type"
            
          >保存
          </el-button>

          <el-button
            type="primary"
            size="mini"
            @click="handleSave"
            v-show="tuiPiaoVal.type != 3"
            v-else
            
          >保存
          </el-button>


          <el-button
            type="warning"
            size="mini"
            @click="handleApprove()"
            v-if="type!=='3'   && !tuiPiaoVal "
            
          >提交
          </el-button>

          <el-button
            type="warning"
            size="mini"
            @click="handleApprove()"
            v-show="tuiPiaoVal.type != 3"
            v-else
          >提交
          </el-button>


          <!--审批相关-->
           <el-button
            type="primary"
            size="mini"
            @click="handleApproveTask(1)"
            v-if="tuiPiaoVal.approve"

          >审批通过
          </el-button>

          <el-button
            type="danger"
            size="mini"
            @click="handleApproveTask(2)"

            v-if="tuiPiaoVal.approve"
          >审批拒绝
          </el-button>


        </div>
      </div>
    </div>
    <template>
      <!---->
         <el-form ref="form" :model="form" label-width="99px"  :rules="rules" >
            
           <h2>{{oldflag}}基本信息</h2>
            <el-row>
              <el-col :span="6" >

                <el-form-item v-if="type != 3" label="开票申请人" prop="createName">
                  <el-input v-model.trim="user.nickName" :disabled="true">
                  </el-input>
                </el-form-item>

                <el-form-item v-else label="开票申请人" prop="createName">
                  <el-input v-model.trim="form.createName" :disabled="true">
                  </el-input>
                </el-form-item>

                

              </el-col>
              

             <el-col :span="12" >



                <el-form-item label="申请部门" prop="deptId" v-if="!oldflag || isTuiPiao">
                  <tree-select v-if="type != 3" :disabled="type == 3 || tuiPiaoVal.type" v-model="form.deptId" :options="departmentAllListData" :normalizer="treeSelectProps"
                     placeholder="选择部门" style="height:22px;line-height:22px;"
                     />

                     <el-input v-else v-model.trim="form.applyDeptName" :disabled="true">
                    </el-input>
                </el-form-item>


                <el-form-item label="申请部门" prop="deptId" v-else>
                  <tree-select  v-model="form.invoiceDeptId" :options="departmentAllListData" :normalizer="treeSelectProps"
                  disabled="true"
                     placeholder="选择部门" style="height:22px;line-height:22px;"
                     />

                </el-form-item>



              </el-col>

              <el-col :span="6" >
                <el-form-item label="费用所属月" prop="expenseMonth">
                    <el-date-picker clearable 
                      size="small" 
                      style="width: 200px"  
                      :disabled="type == 3 || tuiPiaoVal.type"
                      v-model="form.expenseMonth"
                      type="month"
                      value-format="yyyy-MM"
                      placeholder="请选择费用所属月">
                    </el-date-picker>
                  </el-form-item>
              </el-col>

              </el-row>
            <el-row>
          
            <el-col :span="6" >
                <el-form-item label="项目名称" prop="projectName">
                  <el-input v-model.trim="form.projectName" :disabled="type=='3'  || tuiPiaoVal.type"  >
                  </el-input>
                </el-form-item>
              </el-col>
   
            
              <el-col :span="6" >
                <el-form-item label="项目编号" prop="projectNo">
                  <el-input v-model.trim="form.projectNo" :disabled="type=='3'  || tuiPiaoVal.type">
                  </el-input>
                </el-form-item>
              </el-col>

             
              <el-col :span="6" >
                <el-form-item label="合同编号" prop="contractNo">
                  <el-input v-model.trim="form.contractNo" :disabled="type=='3'  || tuiPiaoVal.type">
                  </el-input>
                </el-form-item>
              </el-col>

              


              

            </el-row>

            <h2 style="margin-top:0px;">{{oldflag}}开票信息</h2>
            <el-row>
               <el-col :span="12" >
                <el-form-item label="我方开票公司" prop="ourInvoiceCompany" label-width="120px">
                  <el-select
                    v-model="form.ourInvoiceCompany"
                    placeholder="我方开票公司"
                    clearable
                    size="small"
                    style="width:100%"
                    :disabled="type=='3'  || tuiPiaoVal.type"
                  >
                    <el-option label="请选择我方开票公司" value=""></el-option>
                      <el-option v-for="(item, index) in invoiceCompanyAllListData"
                                :key="`invoiceCompany${index}`"
                                :label="item.dictLabel"
                                :value="item.dictValue">
                      </el-option>
                    
                  </el-select>
                </el-form-item>
              </el-col>
            
            

              <el-col :span="12" >
                <el-form-item label="收票联系人" prop="invoiceReceiverName" label-width="120px">
                  <el-input v-model.trim="form.invoiceReceiverName" :disabled="type=='3'  || tuiPiaoVal.type">
                  </el-input>
                </el-form-item>
              </el-col>

                </el-row>
            <el-row>
            
              <el-col :span="12" >
                <el-form-item label="联系地址" prop="invoiceReceiverAddress" label-width="120px">
                  <el-input v-model.trim="form.invoiceReceiverAddress" :disabled="type=='3'  || tuiPiaoVal.type">
                  </el-input>
                </el-form-item>
              </el-col>
            

              <el-col :span="12" >
                <el-form-item label="联系人电话" prop="invoiceReceiverPhone" label-width="120px" >
                  <el-input v-model.trim="form.invoiceReceiverPhone" :disabled="type=='3'  || tuiPiaoVal.type">
                  </el-input>
                </el-form-item>
              </el-col>


            </el-row>

            <h2 style="margin-top:0px;color:#929191;">{{oldflag}}费用说明</h2>
            <el-row>
                <el-col :span="5" >
                  <el-form-item label="工资费用" prop="salaryExpense">
                    <el-input v-model.trim="form.salaryExpense" :disabled="type=='3'  || tuiPiaoVal.type">
                    </el-input>
                  </el-form-item>
                </el-col>
              <el-col :span="5" >
                  <el-form-item label="社保费用" prop="socialSecurityExpense">
                    <el-input v-model.trim="form.socialSecurityExpense" :disabled="type=='3'  || tuiPiaoVal.type">
                    </el-input>
                  </el-form-item>
                </el-col>

             
                <el-col :span="5" >
                  <el-form-item label="管理费用" prop="managementExpense">
                    <el-input v-model.trim="form.managementExpense" :disabled="type=='3'  || tuiPiaoVal.type">
                    </el-input>
                  </el-form-item>
                </el-col>
           
              <el-col :span="5" >
                 <el-form-item label="其他费用" prop="otherExpense">
                    <el-input v-model.trim="form.otherExpense" :disabled="type=='3'  || tuiPiaoVal.type">
                    </el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="4" >
                 <el-form-item label="合计" prop="totalExpense" label-width="50px">
                    <el-input v-model.trim="totalExpense" :disabled="true">
                    </el-input>
                  </el-form-item>
                </el-col>
            
            </el-row>

            <h2 style="margin-top:0px;color:#929191;">其他信息</h2>

           
           
            
            <el-row v-if="!isTuiPiao">

                <el-col :span="15" >
                  <el-form-item label="开票备注" prop="invoiceRemark" >
                    <el-input  :disabled="type=='3'  || tuiPiaoVal.type" type='textarea' v-model.trim="form.invoiceRemark" class="edit-input" 
                          style="width: 100%"/>

                  </el-form-item>
                  
                  
                </el-col>

            </el-row> 


             <el-row v-else>

                <el-col :span="15" >
                  <el-form-item label="开票备注" prop="remark" >
                    <el-input  :disabled="type=='3'  || tuiPiaoVal.type" type='textarea' v-model.trim="form.remark" class="edit-input" 
                          style="width: 100%"/>

                  </el-form-item>
                  
                  
                </el-col>

            </el-row>
            
            <el-row v-if=" isTuiPiao">

                <el-col :span="15" >
                  <el-form-item label="退票原因" prop="remarkNew" >
                    <el-input  :disabled="(type=='3'  || tuiPiaoVal.type != 2) && !isTuiPiao" type='textarea' v-model.trim="form.remarkNew" class="edit-input" 
                          style="width: 100%"/>

                  </el-form-item>
                  
                  
                </el-col>

            </el-row>

            <el-row v-if="(tuiPiaoVal.type != 2 &&  !isTuiPiao) || tuiPiaoVal.type == 2">

                <el-col :span="15" >
                  <el-form-item label="退票原因" prop="remarkNew" >
                    <el-input  :disabled="(type=='3'  || tuiPiaoVal.type != 2) && !isTuiPiao" type='textarea' v-model.trim="form.remark" class="edit-input" 
                          style="width: 100%"/>

                  </el-form-item>
                  
                  
                </el-col>

            </el-row>

            


            <!-- <el-row>
            <el-col :span="24" style="margin-bottom:100px;">
              <el-form-item label="" prop="applyFiles">
              <div style="display: inline-block;float:left;">
                <ul class="el-upload-list el-upload-list--picture-card" style="float: left; height: 25px;margin-top:-80px;">
                  <li tabindex="0" class="el-upload-list__item"
                      v-for="(item,index) in form.applyFilesListData"
                      :key="`applyFiles${index}`">
                    <p>{{item.fileName}}</p>
                    <div class="el-upload-list__item-actions">
                          <span class="el-upload-list__item-preview" @click="handleExportApplyFiles(item.id)"><i
                            class="el-icon-download"></i></span>
                      <span class="el-upload-list__item-delete" @click="handleRemoveApplyFiles(index)"><i
                        class="el-icon-delete"></i></span>
                    </div>
                  </li>
                </ul>
              </div>
               </el-form-item>
              
              <div id="laborContract-box"
                   style="position: relative; display: inline-block; width: 70px; height: 70px;">
                <div id="upload-laborContract" class="el-upload el-upload--picture-card"
                     style="display: inline-block;">
                  <i class="el-icon-plus"></i>
                </div>
              </div>
            </el-col>
            <el-col :span="24" style="margin-bottom:20px;">
              <div style="color: #999;">提示：请上传PDF文档！</div>
            </el-col>
          </el-row> -->

            <span v-if="type == 3 && !tuiPiaoVal.type" style="" >{{oldflag}}附件列表:</span>
            <el-row style="margin-bottom:40px;">
                <el-col :span="24">
                    <el-upload
                      v-loading="uploadLoading"
                       element-loading-text="正在下载,请稍后..."
                      style="left"
                      class="upload-demo"
                      :action="uploadUrl"
                      :headers="headers"
                      :data="{modelName :'开票申请',employeePhone:'123'}"
                      :on-preview="handlePreview"
                      :on-success="handleSuccess"
                      :on-remove="handleRemove"
                      :before-remove="beforeRemove"
                      :on-error="onError"
                      multiple
                      :limit="100"
                      :on-exceed="handleExceed"
                      :before-upload="beforeUpload"
                      :on-change="handleChange"
                      :file-list="fileList">
                      <el-button v-if="type != 3 &&  tuiPiaoVal.type != 3 && tuiPiaoVal.type != 2" size="small" type="warning">附件上传</el-button>
                      
                      <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
                    </el-upload>
                </el-col>

            </el-row>

            <el-row>
              <el-col :span="24" >

                 <el-button  v-if="type != '3' && !tuiPiaoVal.type" size="small" type="primary" icon="el-icon-add" @click="handleAdd">新增</el-button>

                  <el-table
                    class="list-table"
                    ref="table"
                    :key="tableKey"
                    v-loading="listLoading"
                    :data="listData"
                    stripe
                    size="small"
                    fit
                    show-summary
                    :summary-method="handlePiaoSummaries"
                    highlight-current-row 
                    id="mxlist"
                    >

                    <el-table-column :show-overflow-tooltip="false" prop="receiveCompanyName"
                                    label="" width="250">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">收票单位全称</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input type='textarea' :disabled="type=='3'  || tuiPiaoVal.type" v-model.trim="scope.row.receiveCompanyName" class="edit-input" size="small"
                                    @blur="handleChangeInputValue(scope, 'receiveCompanyName')"
                                    style="width: 230px;"/>
                        </template>
                        
                      </template>
                    </el-table-column>

                    <el-table-column :show-overflow-tooltip="false" prop="taxpayerIdentificationNumber"
                                    label="" width="200">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">纳税人识别号</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input type="textarea" :disabled="type=='3'  || tuiPiaoVal.type" maxlength='18' v-model.trim="scope.row.taxpayerIdentificationNumber" class="edit-input" size="small"
                                    @blur="handleChangeInputValue(scope, 'taxpayerIdentificationNumber')"
                                    style="width: 190px;"/>
                        </template>
                        
                      </template>
                    </el-table-column>

                    <el-table-column :show-overflow-tooltip="false" prop="addressAndPhone"
                                    label="" width="250">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">地址与电话</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input type='textarea'  :disabled="type=='3'  || tuiPiaoVal.type" v-model.trim="scope.row.addressAndPhone" class="edit-input" size="small"
                                    @blur="handleChangeInputValue(scope, 'addressAndPhone')"
                                    style="width: 230px;"/>
                        </template>
                        
                      </template>
                    </el-table-column>

                    <el-table-column :show-overflow-tooltip="false" prop="openingBankAndNo" v-if="!tuiPiaoVal.type"
                                    label="" width="250">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">开户行及账号</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input type='textarea'  :disabled="type=='3'  || tuiPiaoVal.type" v-model.trim="scope.row.openingBankAndNo" class="edit-input" size="small"
                                    @blur="handleChangeInputValue(scope, 'openingBankAndNo')"
                                    style="width: 230px;"/>
                        </template>
                        
                      </template>
                    </el-table-column>

                    <el-table-column :show-overflow-tooltip="false" prop="invoiceTypeFullName" v-if="tuiPiaoVal.type"
                            
                                    label="" width="400">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">开票类型</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input :disabled="tuiPiaoVal.type" type='textarea'  v-model.trim="scope.row.invoiceTypeFullName" class="edit-input" size="small"
                                    style="width: 350px;"/>
                        </template>
                        
                      </template>
                    </el-table-column>


                    <el-table-column :show-overflow-tooltip="false" prop="invoicetype" v-if="!tuiPiaoVal.type"
                                    label="" width="450">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">开票类型</p>
                      </template>
                      <template slot-scope="scope">
                        <template>

                         <el-cascader 
                          :disabled="type=='3'  || tuiPiaoVal.type"
                              v-model="scope.row.invoiceType" 
                              :options="invoiceTypeOptions" 
                              @change="invoiceTypeSelect"
                              style="width:100%"
                              :show-all-levels="true">
                          </el-cascader> 

                          <!-- <el-input v-model="scope.row.invoiceContent" class="edit-input" size="small"
                                    @blur="handleChangeInputValue(scope, 'invoiceContent')"
                                    style="width: 130px;"/> -->
                           <!-- <el-select v-model="scope.row.invoiceType" placeholder="选择开票类型" style="width:160px">
                            <el-option label="选择开票类型" value=""></el-option>
                            <el-option label="代收代付" value="0" />
                           <el-option label="代发工资" value="1" />
                           
                          </el-select> -->

                        </template>
                        
                      </template>
                    </el-table-column>

                    <!-- <el-table-column :show-overflow-tooltip="false" prop="amount"
                                    label="" width="150">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">数量</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input v-model.number="scope.row.amount" class="edit-input" size="small"
                                    @blur="handleChangeInputValue(scope, 'amount')"
                                    style="width: 130px;"/>
                        </template>
                        
                      </template>
                    </el-table-column> -->

                    <el-table-column :show-overflow-tooltip="false" prop="includeTaxMoney"
                                    label="" width="150">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">开票金额（含税）</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input :disabled="type=='3'  || tuiPiaoVal.type" v-model="scope.row.includeTaxMoney" class="edit-input" size="small"
                                    @blur="handleChangeInputValue(scope, 'includeTaxMoney')"
                                  
                                    style="width: 130px;"/>
                        </template>
                        
                      </template>
                    </el-table-column>

                    <el-table-column :show-overflow-tooltip="false" prop="otherMoney"
                                    label="" width="150">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">其中其他金额</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input v-model="scope.row.otherMoney" class="edit-input otherInput" size="small" 
                                    :disabled="scope.row.otherMoneyDisabled || type=='3'  || tuiPiaoVal.type"
                                    @blur="handleChangeInputValue(scope, 'otherMoney')"
                                    style="width: 130px;"/>
                        </template>
                        
                      </template>
                    </el-table-column>

                    <el-table-column :show-overflow-tooltip="false" prop="taxMoney"
                                    label="" width="150">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">税额</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input  v-model="scope.row.taxMoney" class="edit-input" size="small" :disabled="true"
                                    @blur="handleChangeInputValue(scope, ' taxMoney')"
                                    style="width: 130px;"/>
                        </template>
                        
                      </template>
                    </el-table-column>

                    <el-table-column :show-overflow-tooltip="false" prop="remark"
                                    label="" width="150">
                      <template slot="header" slot-scope="{}">
                        <p style="margin: 0;">备注说明</p>
                      </template>
                      <template slot-scope="scope">
                        <template>
                          <el-input type='textarea'  :disabled="type=='3'  || tuiPiaoVal.type" v-model.trim="scope.row.remark" class="edit-input" size="small"
                                    @blur="handleChangeInputValue(scope, 'remark')"
                                    style="width: 130px;"/>
                        </template>
                        
                        
                      </template>
                    </el-table-column>

                    <el-table-column ref="actionColumn" fixed="right" align="left" label="操作" 
                        
                         class-name="small-padding fixed-width">
                      <template slot-scope="scope">
                        <el-button ref="actionDelete"
                                  type="danger"
                                  size="mini"
                                  icon="el-icon-remove"
                                  v-if="type != '3' && !tuiPiaoVal.type"
                                  @click="handleDelete(scope.row,scope.$index)"
                                  ></el-button>
                        <slot name="rights" :row-data="scope.row"></slot>
                      </template>
                    </el-table-column>


                  </el-table>
              </el-col>
            </el-row>

            <!-- <el-row style="margin-top:20px;">
              <el-col :span="8" >
                <el-form-item label="开票时间" prop="pid">
                  <el-input v-model="form.xxx">
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="8" >
                <el-form-item label="邮寄日期" prop="pid">
                  <el-input v-model="form.xxx">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" >
                <el-form-item label="合计开票金额" prop="pid">
                    <el-input v-model="form.xxx">
                    </el-input>
                  </el-form-item>
              </el-col>
            </el-row> -->
            
            
       


        </el-form>

    </template>

    </div>
  </div>
</template>

<script>
  import { debounce } from 'lodash'

  import numeral from 'numeral'
  import commonMixins from '@/mixins/common'
  import salaryMixins from '@/mixins/salary'
  import filters from '@/filters/filters'
  import tagFilter from '@/filters/tagFilter'
  import salaryImportExcel from '@/mixins/salaryImportExcel'

  import { getUserProfile } from "@/api/system/user";
  import TreeSelect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import upload from '@/mixins/upload'
  import {fileDownloadAPI} from '@/api/common.js'

  import { getToken } from '@/utils/auth'
  import { create, all } from 'mathjs'
  import request from '@/utils/request'
  import { formatMoney } from '@/utils/utils'

 

  let baseUrl = process.env.NODE_ENV === 'development' ? `${process.env.VUE_APP_BASE_API}` : `${process.env.VUE_APP_API_PATH}${process.env.VUE_APP_BASE_API}`

  let math = create(all, {
    number: 'BigNumber',
    precision: 64
  })

 let isCurrency = /^(([1-9]\d*)|0)(\.\d{1,2})?$/

  export default {
    name: '',
    mixins: [commonMixins, salaryMixins, filters, tagFilter, salaryImportExcel,upload],
    components: {TreeSelect},
    data() {
      return {
       
        uploadLoading:false,
        handleOkVisible:true,
        isTuiPiao:false,
        leafNodes:[],
        fileList: [] ,
        tuiPiaoVal:{},
        uploadUrl: `${baseUrl}tool/file/uploadFile`,
        headers: {
          Authorization: 'Bearer ' + getToken()
        },

        invoiceTypeOptions:[],

        rules : {

          projectNo: [
              { required: true, message: '请输入项目编号', trigger: 'blur' }
            ],

          contractNo: [
              { required: true, message: '请输入合同编号', trigger: 'blur' }
            ],

          projectName: [
              { required: true, message: '请输入项目名称', trigger: 'blur' }
            ],

          deptId: [
              { required: true, message: '请输入申请部门', trigger: 'blur' }
            ],

            ourInvoiceCompany: [
              { required: true, message: '请输入我方开票公司', trigger: 'blur' }
            ],

            invoiceType: [
              { required: true, message: '请输入发票类型', trigger: 'blur' }
            ],

            invoiceReceiverName: [
              { required: true, message: '请输入收票人姓名', trigger: 'blur' }
            ],

            invoiceReceiverAddress: [
              { required: true, message: '请输入收票人地址', trigger: 'blur' }
            ],

            invoiceReceiverPhone: [
              { required: true, message: '请输入收票人电话', trigger: 'blur' }
            ],

          salaryExpense: [
              {
                required: true, trigger: 'blur', validator: (rule, value, callback) => {
                  if (`${value}` === '') {
                    callback(new Error('请输入工资费用'))
                  } else if (!isCurrency.test(`${value}`)) {
                    callback(new Error('请输入有效的金额'))
                  } else {
                    callback()
                  }
                }
              }
            ],

            socialSecurityExpense: [
              {
                required: true, trigger: 'blur', validator: (rule, value, callback) => {
                  if (`${value}` === '') {
                    callback(new Error('请输入社保费用'))
                  } else if (!isCurrency.test(`${value}`)) {
                    callback(new Error('请输入有效的金额'))
                  } else {
                    callback()
                  }
                }
              }
            ],

            managementExpense: [
              {
                required: true, trigger: 'blur', validator: (rule, value, callback) => {
                  if (`${value}` === '') {
                    callback(new Error('请输入管理费用'))
                  } else if (!isCurrency.test(`${value}`)) {
                    callback(new Error('请输入有效的金额'))
                  } else {
                    callback()
                  }
                }
              }
            ],

             otherExpense: [
              {
                required: true, trigger: 'blur', validator: (rule, value, callback) => {
                  if (`${value}` === '') {
                    callback(new Error('请输入其他费用'))
                  } else if (!isCurrency.test(`${value}`)) {
                    callback(new Error('请输入有效的金额'))
                  } else {
                    callback()
                  }
                }
              }
            ],


        },
        user:{}, //当前登录人
        form:{
          applyFilesListData:[],
        },
        title: this.paramsData.title,
        searchKey: {},
        isExpand: true,
         treeSelectProps(node) {
          return {
            id: node.id,
            label: node.label,
            children: node.children,
            isDefaultExpanded: true
          }
        },
        tableSelectedData: [], // 选中的表数据
        listData: [] // 列表数据
      }
    },
    props: {

      invoiceTypeOptions:{
          type: Array,
          required: true,
          default() {
            return []
          } 
      },
      
      invoiceCompanyAllListData:{
         type: Array,
          required: true,
          default() {
            return []
          } 
      },
      data: { // 列表数据
        type: Array,
        required: true,
        default() {
          return []
        }
      },
      formData:{ 
        type: Object,
        required: true,
        default() {
          return {}
        }
      },
      searchParams: { // 搜索参数
        type: Object,
        required: true,
        default() {
          return {}
        }
      },
      totalCount: {
        type: [String, Number],
        required: true,
        default: 0
      },
      listLoading: {
        type: [Boolean],
        required: true,
        default: false
      },
      type: {
        type: [String],
        required: true,
        default: '1'
      },
      deptName: {
        type: [String],
        default: '-'
      },
      salaryDate: {
        type: [String],
        default: '-'
      },

      paramsData: {
        type: Object,
        required: true,
        default() {
          return {}
        }
      },

      departmentAllListData: {// 搜索参数
        type: Array,
        required: true,
        default() {
          return []
        }
      }
    },
    computed: {

      completedFlag(){
        if(this.form.invoiceStatus  ==  '已退票'){
          return true
        }
        return false
      },

      oldflag(){
        if(this.isTuiPiao || this.tuiPiaoVal.type){
          return "原"
        }
        return ""
      },

      totalExpense() {
        let salaryExpense = this.form.salaryExpense || 0
        let socialSecurityExpense = this.form.socialSecurityExpense || 0
        let managementExpense = this.form.managementExpense || 0
        let otherExpense = this.form.otherExpense || 0
        let result = parseFloat(this.formatNumberTiny({
                formula: `${salaryExpense} + ${socialSecurityExpense} + ${managementExpense} + ${otherExpense}`, format: '0.00'
              }))
        return result
      },

      currentListData() { // 当前的数据列表
        let { listData, totalCount } = this
        let { pageNum, pageSize } = this.searchKey
        let totalPage = 0 //总页数
        if ((totalCount / pageSize) > parseInt(totalCount / pageSize)) {
          totalPage = parseInt(totalCount / pageSize) + 1
        } else {
          totalPage = parseInt(totalCount / pageSize)
        }
        //对数据进行分页
        let startRow = (pageNum - 1) * pageSize
        let endRow = (pageNum * pageSize > totalCount ? totalCount : pageNum * pageSize) - 1
        return listData.filter((item, index) => {
          return startRow <= index && index <= endRow
        })
      }
    },
    methods: {

      handleOk(){

        //判断是否是退票
        if(this.oldflag == '原'){
          
          console.log(this.form)
            let id = this.form.id
            let status = this.form.status - 0
            request({
                url: '/hr/invoice/refund/summary/completed',
                method: 'post',
                data: {
                    id,status
                }
            }).then(response => {
                if (response.code != '200') {
                    this.msgError('操作失败，原因是' + response.msg)
                    return
                }
                //正确的话就隐藏这个按钮
                this.handleOkVisible = false
                  this.msgSuccess('操作成功！')
                history.back();

            })


                return;
        }
         
       
          let id = this.form.id
          let status = this.form.status - 0
          request({
              url: '/hr/invoice/summary/completed',
              method: 'post',
              data: {
                  id,status
              }
          }).then(response => {
              if (response.code != '200') {
                  this.msgError('操作失败，原因是' + response.msg)
                  return
              }
              //正确的话就隐藏这个按钮
              this.handleOkVisible = false
                this.msgSuccess('操作成功！')
              history.back();

          })

      },

      handlePiaoSummaries(param){
            let { listData } = this
            let { columns } = param
            let sums = []
            let keys = ['includeTaxMoney','otherMoney','taxMoney']
            columns.forEach((column, index) => {
              if (index === 0) {
                sums[index] = '合计'
                return
              }
              const values = listData.map(item => item[column.property] || 0)
              if (keys.indexOf(column.property) !== -1 && !values.every(value => isNaN(value))) {
                
                sums[index] = values.reduce((prev, curr) => {
                  let value = Number(curr)
                  if (!isNaN(value)) {
                    let result = math.format(math.evaluate(`${prev} + ${curr}`))
                    return result
                  } else {
                    return prev
                  }
                }, 0)
                sums[index] = formatMoney(sums[index], 2, '') + ' 元'

                // if(column.property == 'includeTaxMoney'){
                //    window.includeTaxMoneyAll = formatMoney(sums[index], 2, '¥').replace('¥','')
                // }

              } else {
                sums[index] = ''
              }
            })
            return sums
        },

        handleChange(file, fileList){
          this.fileList = fileList
         
        },

        onError(err, file, fileList){
          this.$message.warning(err.msg);
        },

        handleRemove(file, fileList) {
          console.log(file, fileList);
          this.fileList = fileList
        },
        handleSuccess(response, file, fileList){
          if(response.code != 200){
            this.$message.warning(response.msg);
            fileList.pop();
            this.fileList = fileList;
          }
        },
        async handlePreview(file) {
          console.log(file);
          this.uploadLoading = true;
          try {
            let response = await fileDownloadAPI({
              fileName: file.response.data.id
            })
            this.downloadFile(response)
          } catch (error) {
            this.$notify.error({
              title: '错误',
              message: error.message || '导出失败!'
            })
          } finally{
            this.uploadLoading = false;
          }
        
        },
        handleExceed(files, fileList) {
          
          //this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
          this.fileList = fileList
        },
        
        beforeUpload(file, fileList){
          let size = file.size / 1024 / 1024;
          console.log(size);
          if(size > 10){
             this.$message.warning(`文件大小为10MB以内！`);
             return false; 
          }
          return true;
        },

        beforeRemove(file, fileList) {
          if(this.type == 3 || tuiPiaoVal.type == 3) return false;
          return this.$confirm(`确定移除 ${ file.name }？`);
        },

      handleExportApplyFiles(data) { // 导出附件
        // this.$emit('on-export', {
        //   name: this.applyFilesName,
        //   fileName: data
        // })
      },

      //  handleRemoveApplyFiles(index) { // 删除
      //   this.form.applyFilesInstance.splice(index, 1)
      //   this.form.applyFilesListData.splice(index, 1)
      // },

      /**
       * 开票明细删除
       */
      handleDelete(data = {},index) {
         this.listData.splice(index,1)
      },

      getUser() {
        getUserProfile().then(response => {
          this.user = response.data;
          //console.log(this.user);
        });
      },

      goBack() {
        // this.$router.push({
        //   name: 'Piao',
        // })
        this.$store.dispatch("tagsView/delView", this.$route);
        history.back()
      },

      //保存前的校验
      beforeSaveFlag(){
          let submitData = {}
         
        //开票明细数据处理
        let listData = this.listData || []
        let fields = ['addressAndPhone','invoiceType','includeTaxMoney','openingBankAndNo','otherMoney','receiveCompanyName','taxpayerIdentificationNumber','taxMoney'];
        let flag = true;
        let errMsg = '';
        for(let i=0;i<listData.length;i++){
            let row = listData[i];
            fields.map((v,k) => { 
                let value = row[v];
                if(!value && value != 0){
                  flag = false;
                  errMsg = '发票明细数据填写不完整，请核对！'
                }

                if('otherMoney' == v || 'includeTaxMoney' == v || 'taxMoney' == v) {
                  // if( !isNumber(row[v])){
                  //   //console.log(row[v] + '不是数字');
                  //   flag = false;
                  //   errMsg = '开票明细中金额填写不正确(最多两位小数)，请核对！'
                  // }
                 
                 if((''+row[v]).split('.')[1] && (''+row[v]).split('.')[1].length > 2){
                   flag = false;
                  errMsg = '开票明细填写不正确(最多两位小数)，请核对！问题数据：' + row[v]
                 }
                  
                }
                //console.log(123)
                if('invoiceType' == v ) {
                    if(!row[v]){
                      flag = false;
                      errMsg = '发票明细数据填写不完整，请核对：发票类型不能为空！'
                    }else{
                      if(row[v][2]) row['invoiceTypeForSave'] = row[v][2]
                    }
                    
                }

              
            });
            
        }
       
        if(!flag){
            this.$notify.error({
                    title: '错误',
                    message: errMsg
                  });
            return false;
        }

        for(let i=0;i<listData.length;i++){
          let row = listData[i];
          row['invoiceType'] = row['invoiceTypeForSave']

        }

        return true;
      },

      handleSave: debounce(function() { // 保存，防抖

      //console.log('文件列表',this.fileList)

       

        if(!this.tuiPiaoVal && !this.beforeSaveFlag() ) return;
        
        //console.log('开票明细',this.listData);   

        if(this.oldflag){
          this.form.deptId=222;
        }
        
        //开票信息表单校验
        this.$refs['form'].validate(valid => {
          if(!valid && !this.oldflag) return;
            let submitData = this.form;

              submitData.hrInvoiceDetails = JSON.parse(JSON.stringify(this.listData)) ;
              let isTuiPiao = this.isTuiPiao;
              
              
              if(this.tuiPiaoVal.type == 2){
                isTuiPiao = true;
              }

             
              //保存附件
              let arr = [];
              if(!this.fileList) this.fileList = []
              for(let i=0;i<this.fileList.length;i++){
                arr.push(this.fileList[i])
              }

              submitData.applyFiles = JSON.stringify(arr)

              let len = submitData.hrInvoiceDetails.length;
              console.log(123334)
              try{
              for(let i=0;i<len;i++){
                if(submitData.hrInvoiceDetails[i].invoiceType.length){
                  console.log(submitData.hrInvoiceDetails[i].invoiceType)
                  submitData.hrInvoiceDetails[i].invoiceType = submitData.hrInvoiceDetails[i].invoiceType[2]
                }
              }
              }catch(e){}
              
              
             this.$emit('on-save',submitData,isTuiPiao)
        });

      }, 300),


      handleApproveTask(option){

        let query = this.$route.query
        let taskId = query.taskId
        let msg = option == 1 ? ' <b><font color=green>通过</font></b> ' : ' <b><font color=red>拒绝</font></b> '

        this.$confirm('审批操作不可撤销,请认真审核,您确定要' + msg + '吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }).then(() => {
          /*let params = this.formatParams()
          this.submitApproveData(params)*/

          if (option == 1) {
            //审批通过就直接提交

            let auditOpinion = prompt('请输入审批意见！');

            request({
              url: '/hr/invoice/refund/apply/audit',
              method: 'post',
              data: {
                taskId: taskId,
                auditOpinion:auditOpinion || '同意',
                auditResult: 1
              }
            }).then(response => {
              if (response.code != '200') {
                this.msgError('审批失败，原因是' + response.data.msg)
                return
              }

              if (response.data.receiveDeptName) {
                this.msgSuccess(response.data.msg + '，下一步办理人【' + response.data.receiveDeptName + '】【' + response.data.receiverName + '】')
              } else {
                this.msgSuccess(response.data.msg)
              }
              //this.msgSuccess(response.data.msg+'，下一步办理人【'+response.data.receiveDeptName+'】【'+response.data.receiverName+'】');
              let that = this
              setTimeout(() => {
                that.goBack()
              }, 2000)

            })

          } else {
            //审批拒绝需要填写拒绝原因
            var auditOpinion = prompt("请输入拒绝原因:");
            if(!auditOpinion){
               this.msgError('拒绝原因不允许为空！');
               return; 
            }
            let query = this.$route.query
            let taskId = query.taskId

            request({
              url: '/hr/invoice/refund/apply/audit',
              method: 'post',
              data: {
                taskId: taskId,
                auditOpinion: auditOpinion,
                auditResult: 0
              }
            }).then(response => {
              if (response.code != '200') {
                this.msgError('审批失败，原因是' + response.data.msg)
                return
              }

              if (response.data.receiveDeptName) {
                this.msgSuccess(response.data.msg + '，下一步办理人【' + response.data.receiveDeptName + '】【' + response.data.receiverName + '】')
              } else {
                this.msgSuccess(response.data.msg)
              }

              let that = this
              setTimeout(() => {
                that.goBack()
              }, 2000)

            })
          }

        })
     
      },


      handleApprove() { // 是否审批

        if(!this.tuiPiaoVal && !this.beforeSaveFlag() ) return;
        //console.log('开票明细',this.listData);   

        //为了绕过deptId的非空验证
        if(this.oldflag){
          this.form.deptId=222;
        }
        //开票信息表单校验
        this.$refs['form'].validate(valid => {
           if(!valid && !this.oldflag) return;
            let submitData = this.form;
              submitData.hrInvoiceDetails = this.listData;

               //保存附件
              let arr = [];
              for(let i=0;i<this.fileList.length;i++){
                arr.push(this.fileList[i])
              }

              submitData.applyFiles = JSON.stringify(arr)

              let isTuiPiao = this.isTuiPiao;
              if(this.tuiPiaoVal.type == 2){
                isTuiPiao = true;
              }
              console.log(678)
              let len = submitData.hrInvoiceDetails.length;
              try{
              for(let i=0;i<len;i++){
                if(submitData.hrInvoiceDetails[i].invoiceType.length){
                  console.log(submitData.hrInvoiceDetails[i].invoiceType)
                  submitData.hrInvoiceDetails[i].invoiceType = submitData.hrInvoiceDetails[i].invoiceType[2]
                }
              }
              }catch(e){}

             this.$emit('on-approve',submitData,isTuiPiao)
        });


        
      },
      handleExport: debounce(function() { // 导出，防抖
        this.$emit('on-export')
      }, 300),

      handleImport() { // 导入
        
        this.$emit('on-import')
      },

      handleAdd(){
        if(!this.listData) this.listData = []
        
        this.listData.push({
                            taxpayerIdentificationNumber:this.listData[0]?this.listData[0].taxpayerIdentificationNumber:'',
                            receiveCompanyName:this.listData[0]?this.listData[0].receiveCompanyName:'',
                            addressAndPhone:this.listData[0]?this.listData[0].addressAndPhone:'',
                            openingBankAndNo:this.listData[0]?this.listData[0].openingBankAndNo:'',
                            includeTaxMoney:0,
                            otherMoney:0,
                            taxRate:0
                          });
      },

      invoiceTypeSelect(node){
        console.log(node)
        this.computeTax()
      },


      //计算税额
      async computeTax(){

          for(let i=0;i<this.listData.length;i++){

              //console.log(i)
              let row = this.listData[i];
              console.log(row)

              //判断是否填写了开票额
              if(!row.includeTaxMoney) 
                continue;
              //判断是否填选择了开票类型
              if(!row.invoiceType)
                continue;
              //根据开票类型去获取公式和税率
              //let node = this.getNode(row.invoiceType,this.invoiceTypeOptions)
              //console.log(i+'---'+row.invoiceType)
              this.listLoading = true;

              //console.log('============',typeof row.invoiceType,row.invoiceType)

              let invoiceType = row.invoiceType;

              if(typeof row.invoiceType == 'object' ){
                invoiceType = row.invoiceType[2];
              }

              let node = await request({
                url: '/system/dict/invoice/' +  invoiceType,
                method: 'get'
              })
               this.listLoading = false;
             node = node.data

             if(node.expression && node.expression.indexOf('otherMoney') != -1){
               //console.log('计算公式有otherMoney，需要填写其他金额！');
                this.$set(this.listData[i], 'otherMoneyDisabled',false);
               
             }else{
                this.$set(this.listData[i], 'otherMoneyDisabled',true);
                 this.listData[i].otherMoney = 0;
             }

              node.expression = node.expression
                                    .replace(new RegExp("includeTaxMoney","gm"),row.includeTaxMoney)
                                      .replace(new RegExp("otherMoney","gm"),row.otherMoney)
                                        .replace(new RegExp("taxRate","gm"),node.taxRate)
              //console.log('最终公式为',node.expression)     

              //计算税率
              //"(includeTaxMoney-otherMoney)/(1+taxRate)*taxRate"
           
               let taxMoney = parseFloat(this.formatNumberTiny({
                formula: `${node.expression}`, format: '0.00'
              }))
              //console.log(taxMoney)
              //row.taxMoney = taxMoney;
              this.$set(this.listData[i], 'taxMoney',taxMoney);

              console.log('重新计算得税率为' + row.taxMoney);
              
          }


      },

      getLeafNodes: invoiceTypeOptions => {
     
        
        for(let i = 0;i<invoiceTypeOptions.length;i++){
          let v = invoiceTypeOptions[i]
          //有孩子节点，则递归
          if(v.children){
            this.getLeafNodes(v.children)
          }
          //无孩子节点，说明是末级节点，暂存起来
          this.leafNodes.push(v)


        }

        return node;
      },


      handleChangeInputValue(data, key) {

        let isCurrency = /^(([1-9]\d*)|0)(\.\d{1,2})?$/
        let { pageNum, pageSize } = this.searchKey
        let { row } = data
        let listDataIndex = (pageNum - 1) * pageSize + data.$index

        //重新计算税额
        if('otherMoney' == key || 'includeTaxMoney' == key || 'taxMoney' == key)
        this.computeTax()
        //console.log('本次修改的行记录为' , row)
        
        this.$set(this.listData[listDataIndex], key, row[key])

        
        
      },
      changeTitle(e) {
        this.$forceUpdate() //我也不明白为什么，就是无法输入，只能这样了
      }
    },
    watch: {
      invoiceTypeOptions: {
         handler: function(newVal, oldVal) {
           // this.getLeafNodes(newVal) 
          if (JSON.stringify(newVal) !== JSON.stringify(this.invoiceTypeOptions)) {
            this.invoiceTypeOptions = JSON.parse(JSON.stringify(newVal))
           
          }
        },
        deep: true,
        immediate: true
      },
      data: {
        handler: function(newVal, oldVal) {
          if (JSON.stringify(newVal) !== JSON.stringify(this.listData)) {
            this.listData = JSON.parse(JSON.stringify(newVal))
            
          }
        },
        deep: true,
        immediate: true
      },
      formData: {
        handler: function(newVal, oldVal) {
          console.log(newVal)
          
          if(newVal.invoiceStatus == '已开票' || newVal.status - 0 >= 20){
            this.handleOkVisible = false
          }
          

          if (JSON.stringify(newVal) !== JSON.stringify(this.form)) {
            //console.log(newVal)
            this.form = JSON.parse(JSON.stringify(newVal))
            
            //处理附件
            //this.applyFiles = JSON.parse(this.form.applyFiles);
            //console.log(this.form.applyFiles)
            this.fileList = JSON.parse(this.form.applyFiles)
            //console.log(this.fileList)

            this.listData = this.form.hrInvoiceDetails
            
            //回显开票类型
            for(let i=0;i<this.listData.length;i++){
                let row = this.listData[i];
                row.invoiceType = row.invoiceTypePids.split(',');
                //console.log(row.invoiceType)
            }
            
            //this.form.invoiceType = this.form.invoiceTypePids.split(',')


            console.log(123)
            if(this.paramsData.rows){
              this.isTuiPiao = true
              let rows = JSON.parse(this.paramsData.rows);
              for(let i = 0;i<this.listData.length;i++){
                let id = this.listData[i].id;
                if(rows.indexOf(id)==-1){
                  this.listData.splice(i,1)
                  i--
                }
              }
            }

          }
        },
        deep: true,
        immediate: true
      },

      searchParams: {
        handler: function(newVal, oldVal) {
          if (JSON.stringify(newVal) !== JSON.stringify(this.searchKey)) {
            this.searchKey = JSON.parse(JSON.stringify(newVal))
          }
        },
        deep: true,
        immediate: true
      },

      paramsData: {

        handler: function(newVal, oldVal) {
           //console.log(newVal)   yyf
           console.log('这里是piaomakeTable里面的paramsData监听');

           //如果有退票参数传过来，说明是退票业务，则将退票数据存入tuiPiaoVal
           if(newVal.tuiPiao){
             this.tuiPiaoVal = newVal;

             let that = this;
              request({
                  url: '/hr/invoice/refund/apply/' + newVal.id,
                  method: 'get'
              }).then(response => {
                 that.form = response.data
                 this.listData = response.data.hrInvoiceRefundDetails
              })



             return;
           }
           
          if (JSON.stringify(newVal) !== JSON.stringify(this.paramsData)) {
            
            console.log(newVal)
            this.paramsData = JSON.parse(JSON.stringify(newVal))



          }
        },
        deep: true,
        immediate: true
      }
    },
    created() {
      
    },
    mounted() {
      this.getTableColumns()
      this.getUser()
      //console.log(this.formData)
      
    }
  }


  function isNumber(val){

          var regPos = /^\d+(\.\d+)?$/; //非负浮点数
          var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
          if(regPos.test(val) || regNeg.test(val)){
              return true;
          }else{
              return false;
          }

      }
</script>

<style lang="scss" >
  .list-table {
    .el-button--mini {
      padding: 7px 15px;
      width: 45px;
      color: #fff;
    }

    & /deep/ .el-table__header-wrapper {
      th {
        background-color: #fff;
      }
    }
  }

  .piaomake {

  h2 {
    font-size: 18px;
    font-weight: 500;
    border-bottom: 1px solid #eaeaea;
    padding-bottom: 4px;
    margin-top:0px;color:#929191;
  }

   .el-popover {
    max-height: 400px;
    overflow-x: auto;
    overflow-y: scroll;
  }

  .goTop {
    display: inline-block;
    padding: 14px 2px;
    background: #eaeaea;
    border: 1px solid #ccc;
    position: fixed;
    right: 2px;
    bottom: 280px;
    z-index: 8;
    cursor: pointer;
  }

  .el-form-item__label {
      font-size: 13px;
  }

  .el-input--medium .el-input__inner {
    height: 30px;
    line-height: 30px;
}

.el-upload-list {
    margin: 0;
    padding: 0;
    list-style: none;
    float: left;
}

.el-upload-list__item {
  width: auto;
  margin-right: 20px;
  padding: 2px 6px;
  border: 1px solid #ccc;
  display: inline-block;
}

.el-upload-list__item-name {
  display: inline;
}

.el-upload {
    display: inline-block;
    text-align: center;
    cursor: pointer;
    outline: none;
    float: left;
    margin-right: 10px;
    margin-top: 10px;
    margin-left: 20px;
    
}



.el-input.is-disabled .el-input__inner {
    background-color: #F5F7FA;
    border-color: #dfe4ed;
    color: #000001 !important;
   

}

.el-textarea__inner {
    background-color: #FFF;
    border-color: #dfe4ed;
    color: #000001 !important;
    

}

.el-input.is-disabled .el-input__inner {
    background-color: #F5F7FA;
    border-color: #dfe4ed;
    color: #000;

}

.el-table .fixed-width .el-button--mini {
    color: #fff;
    padding: 6px 16px;
    width: inherit;
}

}

</style>

